<!--
 * @description: 角色设定
 * @fileName: CharacterDesign
 * @author: 17076
 * @date: 2025/2/21-下午1:34
 * @version: V1.0.0
-->

<template>
  <div style="height: 100%;margin-top: 10px">
    <el-row :gutter="10">
      <el-col :span="8">
        <base-card :title="`角色列表（${ roleList.length }）`">
          <template slot="right">
            <div style="text-align: right">
              <el-button @click="handleAddRole">添加角色</el-button>
              <el-button :loading="isLoading" @click="handleExtractRoles">重新获取</el-button>
            </div>
          </template>
          <div class="left-roles" :style="{ height: $baseTableHeight(-45) + 'px' }">
            <div v-if="roleList.length > 0 && !isLoading" class="role-list-content">
              <div v-for="item in roleList" :key="item.id" :class="['flex-row', 'role-item', currentRoles === item.id ? 'active' : '']" @click="handleSelect(item)">
                <el-image :src="downloadUrl + item.fileId">
                  <div slot="error" class="flex-column flex-center error-content">
                    <i class="el-icon-picture-outline"/>
                    <span>暂无图片</span>
                  </div>
                </el-image>
                <div class="flex-column role-info">
                  <div>{{ `角色名称: ${item['name']}` }}</div>
                  <div>{{ `声音: ${ item['voiceName'] ? item['voiceName']: '-' }` }}</div>
                  <div>{{ `角色描述: ${item['remark'] ? item['remark'] : '-'}` }}</div>
                </div>
                <div class="right-buttons">
                  <i class="el-icon-edit edit-icon" title="编辑" @click.stop="handleEdit(item)" />
                  <i class="el-icon-delete delete-icon" title="删除" @click.stop="handleDelete(item)" />
                </div>
              </div>
            </div>
            <el-empty v-if="!isLoading && roleList.length === 0" description="暂无角色数据" style="height: 100%">
              <template slot="image">
                <img src="@/assets/common/empty_role.png"/>
              </template>
            </el-empty>
            <template v-if="isLoading">
              <div class="flex-column flex-center rebuild-loading-content">
                <img src="~@/assets/write/loading.gif">
                <span>角色提取中..</span>
              </div>
            </template>
          </div>
        </base-card>
      </el-col>
      <el-col :span="16">
        <base-card title="角色形象">
          <template slot="right">
            <el-button v-if="rolesHistoryList.length > 0" plain @click="handleRoleImage">编辑角色形象</el-button>
          </template>
          <div class="right-content" :style="{ height: $baseTableHeight(-60) + 'px' }">
            <template v-if="rolesHistoryList.length > 0">
              <div v-for="(item, index) in rolesHistoryList" :key="index">
                <p>{{ item.dress }}</p>
                <el-row :gutter="10">
                  <el-col v-for="(angle, angleIndex) in item.images" :key="angleIndex" :span="6">
                    <div v-if="angle['fileId']" class="flex-column" style="align-items: center">
                      <el-image :src="downloadUrl + angle.fileId" fit="contain" class="right-angle-image" />
                      <span style="margin-top: 10px">{{ angle['angle'] }}</span>
                    </div>
                  </el-col>
                </el-row>
              </div>
            </template>
            <el-empty v-else description="暂无角色形象" style="height: 100%">
              <template slot="image">
                <img src="@/assets/common/empty_role.png"/>
              </template>
              <el-button plain @click="handleAddRoleImage">添加角色形象</el-button>
            </el-empty>
          </div>
        </base-card>
      </el-col>
    </el-row>
    <!--添加角色形象-->
    <role-image ref="image" @reload="handleViewRoles" />
    <!--添加角色-->
    <add-roles ref="add" :play-id="playId" @reload="handleViewRoles" />
  </div>
</template>

<script>

import RoleImage from './RoleImage.vue'
import { selectByPlayRoleId, selectPlayRole, deletePlayRoles } from '@/api/roles'
import { baseURL } from '@/config'
import { commonDownloadFile } from '@/api/config/uploadApi'
import AddRoles from './AddRoles.vue'
import RolesList from './RolesList.vue'
import { mapActions, mapGetters } from 'vuex'
import { getPlayRole } from '@/api/play'
export default {
  name: 'CharacterDesign',
  components: { RolesList, AddRoles, RoleImage },
  props: {
    // 剧本id
    playId: {
      type: String || Number,
      default: 0
    }
  },
  data() {
    return {
      // 风格类型
      typeList: [],
      // 角色列表
      roleList: [],
      // 角色设置列表
      rolesHistoryList: [],
      // 角色提取中
      isLoading: false,
      // 当前选中的角色
      currentRoles: '',
      // 文件下载链接
      downloadUrl: baseURL + commonDownloadFile,
      // 角色表单
      rolesForm: {}
    }
  },
  computed: {
    // 剧本状态
    ...mapGetters({
      playStatus: 'lens/playStatus',
      username: 'user/username'
    })
  },
  mounted() {
    this.handleViewRoles()
    // 表单添加剧本id
    this.$set(this.rolesForm, 'playId', this.playId)
  },
  methods: {
    ...mapActions({
      changeShowNext2: 'lens/changeShowNext2'
    }),
    // 查看剧本角色
    handleViewRoles() {
      if (!this.playId) {
        this.$baseMessage.error('剧本不存在,请上传剧本!')
        return
      }
      selectPlayRole({ playId: this.playId }).then(res => {
        if (res.data.result.length > 0) {
          this.changeShowNext2(true)
          this.roleList = res.data.result
          this.currentRoles = this.roleList[0]['id']
          this.rolesForm = this.$baseLodash.cloneDeep(this.roleList[0])
          this.getRolesImages()
        } else {
          this.handleExtractRoles()
        }
      })
    },
    // 选中角色
    handleSelect(item) {
      if (this.currentRoles === item.id) return
      this.currentRoles = item.id
      this.rolesForm = this.$baseLodash.cloneDeep(item)
      this.getRolesImages()
    },
    // 获取角色形象
    getRolesImages() {
      selectByPlayRoleId({ playRoleId: this.currentRoles }).then(res => {
        this.rolesHistoryList = res.data
      })
    },
    // 删除角色
    handleDelete(item) {
      this.$baseConfirm('确定删除该角色?', '提示', async() => {
        const { code, msg } = await deletePlayRoles({ id: item.id })
        code === 200 ? this.$baseMessage.success(msg || '删除成功') : this.$baseMessage.error(msg || '删除失败')
        this.handleViewRoles()
      })
    },
    // 编辑角色数据
    handleEdit(item) {
      this.$refs.add.show(item, true)
    },
    // 添加角色
    handleAddRole() {
      // 如果正在提取角色，不能手动添加，否则会出现添加的角色被删除的情况
      if (this.isLoading) {
        this.$baseMessage.error('角色提取中,请稍后再试!')
        return
      }
      this.$refs.add.show(null, false)
    },
    // 添加角色形象
    handleAddRoleImage() {
      if (!this.currentRoles || this.currentRoles === '') {
        this.$baseMessage.error('请先选择角色!')
        return
      }
      this.$refs.image.show(this.rolesForm, false)
    },
    // 编辑角色形象
    handleRoleImage() {
      this.$refs.image.show({ ...this.rolesForm, playRoleImages: this.rolesHistoryList }, true)
    },
    // 提取角色
    handleExtractRoles() {
      if (this.roleList.length > 0) {
        this.$baseConfirm('重新获取会清空当前角色列表且无法恢复，点击【确认】继续当前操作?', '', async() => {
          this.handleQueryRoles()
        })
      } else {
        this.handleQueryRoles()
      }
    },
    // 角色提取中
    handleQueryRoles() {
      this.isLoading = true
      getPlayRole({ id: this.playId }).then(res => {
        this.isLoading = false
        this.roleList = res.data
      }).catch(() => {
        this.isLoading = false
      })
    }
  }
}
</script>

<style scoped lang="scss">
.left-roles {
  flex: 1;
  padding: 10px;
  box-sizing: border-box;
  color: #FFFFFF;
  background: $base-content-background;
  border-radius: 8px;
  .role-list-content {
    height: 100%;
    overflow-y: auto;
    overflow-x: hidden;
    margin-top: 10px;
    .role-item {
      position: relative;
      margin-bottom: 10px;
      padding: 10px;
      box-sizing: border-box;
      border-radius: 8px;
      align-items: center;
      border: 1px solid #39414E;
      background: #272C36;
      cursor: pointer;
      ::v-deep {
        .el-image {
          width: 100px;
          height: 160px;
        }
      }
      .role-info {
        flex: 1;
        margin-left: 10px;
        >div {
          line-height: 20px;
          margin-bottom: 10px;
        }
      }
      .edit-icon {
        position: absolute;
        right: 40px;
        top: 10px;
        cursor: pointer;
      }
      .delete-icon {
        position: absolute;
        right: 10px;
        top: 10px;
        cursor: pointer;
      }
      .right-buttons {
        display: none;
      }
      &:hover {
        .right-buttons {
          display: flex;
        }
      }
    }
    .active {
      border-color: $base-color-default;
    }
  }
  .rebuild-loading-content {
    height: calc(100% - 50px);
    >img {
      width: 40px;
      height: 40px;
    }
    >span {
      margin-top: 5px;
      font-size: 12px;
      color: #B6C7D1;
    }
  }
}
.right-content {
  color: #FFFFFF;
  background: $base-content-background;
  overflow-y: auto;
  .right-angle-image {
    width: 100%;
    max-height: 100%;
    aspect-ratio: 1 / 1;
    border-radius: 8px;
    object-fit: contain;
  }
}
</style>
